package com.example.xd.myijkplayer.my

import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.content.Context
import android.content.res.TypedArray
import android.net.Uri
import android.os.Build
import android.os.Handler
import android.os.Message
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.view.SurfaceHolder
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.view.animation.LinearInterpolator
import android.widget.FrameLayout
import android.widget.SeekBar
import androidx.annotation.RequiresApi
import com.example.xd.myijkplayer.R
import com.example.xd.myijkplayer.utils.TimeFormatUtil
import kotlinx.android.synthetic.main.item_player_layout.view.*
import tv.danmaku.ijk.media.exo.IjkExoMediaPlayer
import tv.danmaku.ijk.media.player.IMediaPlayer
import tv.danmaku.ijk.media.player.IjkTimedText

/**
 * @auther XuDan on 2020/9/11.
 */
class ItemPlayerView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr), IControl, SurfaceHolder.Callback,
    IMediaPlayer.OnPreparedListener, View.OnClickListener, SeekBar.OnSeekBarChangeListener,
    IMediaPlayer.OnTimedTextListener, IMediaPlayer.OnBufferingUpdateListener,
    IMediaPlayer.OnCompletionListener, IMediaPlayer.OnErrorListener, IMediaPlayer.OnInfoListener,
    IMediaPlayer.OnVideoSizeChangedListener, IMediaPlayer.OnSeekCompleteListener {
    init {
        initView(context, attrs)
    }

    private fun initView(context: Context, attrs: AttributeSet?) {
        LayoutInflater.from(context).inflate(R.layout.item_player_layout, this, true)
        val typedArray: TypedArray =
            context.obtainStyledAttributes(attrs, R.styleable.ItemPlayerView)
        val isShowFl = typedArray.getBoolean(R.styleable.ItemPlayerView_is_show_fl, true)
        if (isShowFl) {
            item_palyer_fl.visibility = View.VISIBLE
        } else {
            item_palyer_fl.visibility = View.GONE
        }
        typedArray.recycle()
        item_palyer_left_check_img.setOnClickListener(this)
        item_palyer_scal_img.setOnClickListener(this)
        item_palyer_seekBar.setOnSeekBarChangeListener(this)
        item_play_sf.holder.addCallback(this)
        item_player_img_pause.setOnClickListener(this)
    }

    private lateinit var mediaPlayer: IjkExoMediaPlayer
    fun setIjkExoMediaPlayer(player: IjkExoMediaPlayer) {
        this.mediaPlayer = player
    }

    fun setPath(path: String) {
        mediaPlayer.setDataSource(context, Uri.parse(path))
    }

    var w = 0
    var h = 0
    var full_w = 0
    var full_h = 0
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        full_w = MeasureSpec.getSize(widthMeasureSpec)
        full_h = MeasureSpec.getSize(heightMeasureSpec)
        w = full_w
        h = w * 6 / 9
        setMeasuredDimension(w, h)
    }

    var timeHandler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                1 -> {
                    if (isPlaying()) {
                        val obtain = Message.obtain()
                        obtain.what = 1
                        sendMessageDelayed(obtain, 1000)
                        item_palyer_time_tv.setText(
                            TimeFormatUtil.stringForTime(currentPosition()) + "/" + TimeFormatUtil.stringForTime(
                                duration()
                            )
                        )
                        item_palyer_seekBar.setProgress((currentPosition() * 100 / duration()).toInt())
                    }
                }
            }
        }
    }

    override fun start() {
        mediaPlayer.start()
        item_player_img_pause.visibility = View.GONE
        item_palyer_left_check_img.setImageResource(R.drawable.ag_btn_movie_stop_bottom)
        val obtain = Message.obtain()
        obtain.what = 1
        timeHandler.sendMessage(obtain)
    }

    override fun restart() {
        mediaPlayer.start()
        item_palyer_left_check_img.setImageResource(R.drawable.ag_btn_movie_stop_bottom)
        item_player_img_pause.visibility = View.GONE
        val obtain = Message.obtain()
        obtain.what = 1
        timeHandler.sendMessage(obtain)
    }

    private var isPlayerPause = false
    override fun pause() {
        mediaPlayer.pause()
        item_palyer_left_check_img.setImageResource(R.drawable.ag_btn_movie_play_bottom)
        item_player_img_pause.visibility = View.VISIBLE
        val obtain = Message.obtain()
        obtain.what = 1
        timeHandler.sendMessage(obtain)
        isPlayerPause = true
    }

    override fun seekTo(pos: Long) {
        mediaPlayer.seekTo(pos)
    }

    override fun isIdle(): Boolean {
        return !mediaPlayer.isPlaying
    }

    override fun isPreparing(): Boolean {
        return !isPerpare
    }

    override fun isPrepared(): Boolean {
        return isPerpare
    }

    override fun isBufferingPlaying(): Boolean {
        TODO("Not yet implemented")
    }

    override fun isBufferingPaused(): Boolean {
        TODO("Not yet implemented")
    }

    override fun isPlaying(): Boolean {
        return mediaPlayer.isPlaying
    }

    override fun isPaused(): Boolean {
        return isPlayerPause
    }

    override fun isError(): Boolean {
        return isPlayerError
    }

    override fun isCompleted(): Boolean {
        return isPlayerCompleted
    }

    override fun isFullScreen(): Boolean {
        return isfullScreen
    }

    override fun isTinyWindow(): Boolean {
        TODO("Not yet implemented")
    }

    override fun isNormal(): Boolean {
        TODO("Not yet implemented")
    }

    override fun duration(): Long {
        return mediaPlayer.duration
    }

    override fun currentPosition(): Long {
        var p: Long = mediaPlayer.currentPosition
        if (p === 0L) {
            return 1
        } else {
            return p
        }
    }

    override fun bufferPercentage(): Int {
        TODO("Not yet implemented")
    }

    override fun enterFullScreen() {
        val animatorSet = AnimatorSet()
        var rotateAnimator: ObjectAnimator =
            ObjectAnimator.ofFloat(item_player_full_fl, "rotation", 90F);//图片默认X轴旋转
        val scalXanimator: ObjectAnimator =
            ObjectAnimator.ofFloat(
                item_player_full_fl,
                "scaleX",
                full_w.toFloat() / h.toFloat()
            )
        val scalYanimator: ObjectAnimator =
            ObjectAnimator.ofFloat(item_player_full_fl, "scaleY", full_h.toFloat() / w.toFloat())
        animatorSet.playTogether(rotateAnimator, scalXanimator, scalYanimator)
        animatorSet.duration = 100
        animatorSet.start()
    }

    override fun exitFullScreen() {
        val animatorSet = AnimatorSet()
        var rotateAnimator: ObjectAnimator =
            ObjectAnimator.ofFloat(item_player_full_fl, "rotation", -90F);//图片默认X轴旋转
        val scalXanimator: ObjectAnimator =
            ObjectAnimator.ofFloat(item_player_full_fl, "scaleX", w.toFloat() / full_h.toFloat())
        val scalYanimator: ObjectAnimator =
            ObjectAnimator.ofFloat(item_player_full_fl, "scaleY", h.toFloat() / full_w.toFloat())
        animatorSet.playTogether(rotateAnimator, scalXanimator, scalYanimator)
        animatorSet.duration = 100
        animatorSet.start()//开始执行动画(图片X轴旋转)
    }

    override fun enterTinyWindow() {
        TODO("Not yet implemented")
    }

    override fun exitTinyWindow(): Boolean {
        TODO("Not yet implemented")
    }

    override fun release() {
        mediaPlayer.release()
    }

    override fun surfaceChanged(holder: SurfaceHolder?, format: Int, width: Int, height: Int) {
        if (isfullScreen) {
            holder?.setFixedSize(full_h, full_w)
        } else {
            holder?.setFixedSize(w, h)
        }
        mediaPlayer.setSurface(holder?.surface)
    }

    override fun surfaceDestroyed(holder: SurfaceHolder?) {
    }

    override fun surfaceCreated(holder: SurfaceHolder?) {
        holder?.setFixedSize(w, h)
        mediaPlayer.setDisplay(holder)
        mediaPlayer.setOnPreparedListener(this)
        mediaPlayer.setOnBufferingUpdateListener(this)
        mediaPlayer.setOnCompletionListener(this)
        mediaPlayer.setOnErrorListener(this)
        mediaPlayer.setOnInfoListener(this)
        mediaPlayer.setOnVideoSizeChangedListener(this)
        mediaPlayer.setOnTimedTextListener(this)
        mediaPlayer.setOnSeekCompleteListener(this)
        mediaPlayer.prepareAsync()
        startLoadingAnim()
    }

    lateinit var rotateAnimation: Animation
    private fun startLoadingAnim() {
        if (rotateAnimation == null) {
            rotateAnimation = AnimationUtils.loadAnimation(context, R.anim.loading_rotate)
            val lin = LinearInterpolator()
            rotateAnimation.setInterpolator(lin)
            item_player_img_loading.animation = rotateAnimation
            item_player_img_loading.startAnimation(rotateAnimation)
        } else {
            item_player_img_loading.startAnimation(rotateAnimation)
        }
    }

    private fun stopLoadingAnim() {
        item_player_img_loading.clearAnimation()
        item_player_img_loading.visibility = View.GONE
        item_player_img_pause.visibility = View.VISIBLE

    }

    private var isPerpare = false
    override fun onPrepared(mediaPlayer: IMediaPlayer?) {
        isPerpare = true
        stopLoadingAnim()
        item_palyer_time_tv.setText("00:00/" + TimeFormatUtil.stringForTime(duration()))
        item_palyer_seekBar.setProgress(0)
        item_palyer_seekBar.secondaryProgress = 0
        item_palyer_seekBar.max = 100
    }


    private var isfullScreen = false
    override fun onClick(v: View?) {
        when (v) {
            item_palyer_left_check_img -> {
                if (mediaPlayer.isPlaying) {
                    pause()
                } else {
                    restart()
                }
            }
            item_palyer_scal_img -> {
                isfullScreen = !isfullScreen
                if (isfullScreen) {
                    exitFullScreen()
                } else {
                    enterFullScreen()
                }
            }
            item_player_img_pause -> {
                if (isPerpare) {
                    start()
                }
            }
        }
    }

    override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {

    }

    override fun onStartTrackingTouch(seekBar: SeekBar?) {

    }

    override fun onStopTrackingTouch(seekBar: SeekBar?) {
        var progress = seekBar?.progress
        val l = duration() * progress!! / 100
        seekTo(l)
    }

    @RequiresApi(Build.VERSION_CODES.N)
    override fun onBufferingUpdate(mediaPlayer: IMediaPlayer?, i: Int) {
        item_palyer_seekBar.secondaryProgress = (i * 100 / duration()).toInt()
    }

    override fun onTimedText(p0: IMediaPlayer?, p1: IjkTimedText?) {

    }

    private var isPlayerCompleted = false
    override fun onCompletion(p0: IMediaPlayer?) {
        isPlayerCompleted = true
        seekTo(0)
        pause()
        item_palyer_time_tv.setText("00:00/" + TimeFormatUtil.stringForTime(duration()))
        item_palyer_seekBar.setProgress(0)
    }

    private var isPlayerError = false

    override fun onError(mediaPlayer: IMediaPlayer?, p1: Int, p2: Int): Boolean {
        isPlayerError = true
        return isPlayerError
    }

    override fun onInfo(p0: IMediaPlayer?, p1: Int, p2: Int): Boolean {
        return true
    }

    override fun onVideoSizeChanged(p0: IMediaPlayer?, p1: Int, p2: Int, p3: Int, p4: Int) {

    }

    override fun onSeekComplete(p0: IMediaPlayer?) {

    }
}